﻿using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace PengSW.ImageHelper
{
    public class ImageRawData
    {
        public ImageRawData(BitmapSource aImageSource, PixelFormat aPixelFormat)
        {
            // 转换为指定格式
            FormatConvertedBitmap aFormatedImage = new FormatConvertedBitmap(aImageSource, aPixelFormat, null, 0);

            // 提取图片数据
            int aStride = (aFormatedImage.Format.BitsPerPixel * aFormatedImage.PixelWidth + 7) / 8;
            byte[] aSourceRawData = new byte[aStride * aFormatedImage.PixelHeight];
            aFormatedImage.CopyPixels(aSourceRawData, aStride, 0);

            RawData = aSourceRawData;
            PixelWidth = aFormatedImage.PixelWidth;
            PixelHeight = aFormatedImage.PixelHeight;
            BitsPerPixel = aFormatedImage.Format.BitsPerPixel;
            Stride = aStride;
            DpiX = aFormatedImage.DpiX;
            DpiY = aFormatedImage.DpiY;
            Format = aFormatedImage.Format;
            Palette = aFormatedImage.Palette;
        }
        public byte[] RawData { get; }
        public int Size => RawData.Length;
        public int PixelWidth { get; }
        public int PixelHeight { get; }
        public int BitsPerPixel { get; }
        public int Stride { get; }
        public double DpiX { get; }
        public double DpiY { get; }
        public PixelFormat Format { get; }
        public BitmapPalette Palette { get; }
        public ImageSource CreateImage()
        {
            // 生成结果图片
            BitmapSource aImageFromRawData = BitmapImage.Create(PixelWidth, PixelHeight, DpiX, DpiY, Format, Palette, RawData, Stride);
            return aImageFromRawData;
        }
    }
}
